﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using AuthenticationLibrary.DataBaseModel;


namespace AuthenticationLibrary
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class AuthenticationService : IAuthenticationService
    {
        #region Field
            ServerIIDataBaseModelContainer db = new ServerIIDataBaseModelContainer();
            const String error = "NULL";
        #endregion

        public bool IsParamsNull(List<String> parameters)
        {
            foreach (String str in parameters)
            {
                if (String.IsNullOrWhiteSpace(str)) return true;
            }
            return false;
        }

        public bool IsUserExist(string email, string password)
        {
            if (IsParamsNull(new List<string> { email, password })) return false;
            var res = (from user in db.Users
                        where user.Email == email && user.Password == password
                        select user.Name).ToList();
            if (res.Count == 0) return false;
            return (String.IsNullOrWhiteSpace(res[0])) ? (false) : (true);
        }

        public List<String> GetUserIdentifier(string question, string answer)
        {
            if (IsParamsNull(new List<string> { question, answer })) return new List<string> { error };
            var u = (from user in db.Users where user.Question == question && user.Answer == answer select user).ToList();
            if (u.Count == 0) return new List<string> { error };
            return (new List<String> { u[0].Name, u[0].Email, u[0].Password });
        }

        public bool TryToRestoreUser(string question, string answer)
        {
            if (IsParamsNull(new List<string> { question, answer })) return false;
            var res = (from user in db.Users
                        where user.Question == question && user.Answer == answer
                        select user.Email).ToList();
            if (res.Count == 0) return false;
            return (String.IsNullOrWhiteSpace(res[0])) ? (false) : (true);
        }

        public bool RegisterUser(string email, string password, string question, string answer)
        {
            if (IsParamsNull(new List<string> { email, password, question, answer })) return false;

            char[] delim = new char[] { '@' };
            String[] tab = email.Split(delim, StringSplitOptions.None);

            User u = new User();
            u.Name = tab[0];
            u.Email = email;
            u.Password = password;
            u.Question = question;
            u.Answer = answer;
            db.AddToUsers(u);
            db.SaveChanges();
            return true;
        }
    }
}
